package com.pm.service.impl;

import com.pm.entity.Task;
import com.pm.mapper.TaskMapper;
import com.pm.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务服务实现类
 */
@Service
public class TaskServiceImpl implements TaskService {
    
    @Autowired
    private TaskMapper taskMapper;
    
    @Override
    public Task createTask(Task task) {
        task.setCreatedAt(LocalDateTime.now().toString());
        task.setUpdatedAt(LocalDateTime.now().toString());
        if (task.getStatus() == null) {
            task.setStatus("TODO");
        }
        if (task.getPriority() == null) {
            task.setPriority("MEDIUM");
        }
        taskMapper.insert(task);
        return task;
    }
    
    @Override
    public Task updateTask(Task task) {
        task.setUpdatedAt(LocalDateTime.now().toString());
        taskMapper.updateById(task);
        return task;
    }
    
    @Override
    public boolean deleteTask(String id) {
        return taskMapper.deleteById(id) > 0;
    }
    
    @Override
    public Task findById(String id) {
        return taskMapper.selectById(id);
    }
    
    @Override
    public List<Task> getAllTasks() {
        return taskMapper.selectList(null);
    }
    
    @Override
    public List<Task> findByProjectId(String projectId) {
        return taskMapper.findByProjectId(projectId);
    }
    
    @Override
    public List<Task> findByAssigneeId(String assigneeId) {
        return taskMapper.findByAssigneeId(assigneeId);
    }
    
    @Override
    public List<Task> findByCreatorId(String creatorId) {
        return taskMapper.findByCreatorId(creatorId);
    }
    
    @Override
    public List<Task> findByStatus(String status) {
        return taskMapper.findByStatus(status);
    }
    
    @Override
    public boolean updateTaskStatus(String id, String status) {
        Task task = findById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        task.setStatus(status);
        task.setUpdatedAt(LocalDateTime.now().toString());
        
        return taskMapper.updateById(task) > 0;
    }
    
    @Override
    public boolean assignTask(String id, String assigneeId) {
        Task task = findById(id);
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        
        task.setAssigneeId(assigneeId);
        task.setUpdatedAt(LocalDateTime.now().toString());
        
        return taskMapper.updateById(task) > 0;
    }
}